package com.example.demo.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.demo.dao.model.UserProfile;
import com.example.demo.dao.model.Users;
import com.example.demo.validation.UserParams;

@Mapper
public interface UserMapper {

	@Select("select count(*) from users where id > 0")
	public Integer getCount();
	
	@Select("select * from users where #{cond}='' or user_code=#{cond} or name like concat('%', #{cond}, '%') or age=#{cond}")
	public List<Users> getUserListByCondition(String cond);
	
	@Select("select * from users where user_code=#{userCode}")
	public Users getUserByCode(String userCode);
	
	@Select("select * from user_profile where user_code=#{userCode}")
	public UserProfile getUserProfileByCode(String userCode);
	
	@Select("select "
			+ "u.user_code as user_code,"
			+ "u.name as name,"
			+ "u.age as age,"
			+ "p.nickname as nickname,"
			+ "p.amount as amount,"
			+ "p.is_vip as is_vip "
			+ "from users as u "
			+ "inner join user_profile as p on p.user_code=u.user_code "
			+ "where "
			+ "u.user_code=#{userCode}")
	public Map<String, Object> getProfileByUserCode(String userCode);
	
	@Insert({
		"<script> ",
		"insert into users ",
		"(id,user_code,name,age,create_time,create_user,update_time,update_user,ip) ",
		"values ",
		"<foreach collection='items' item='item' index='index' separator=','>", 
		"(null,#{item.user_code},#{item.name},#{item.age},now(),#{item.create_user},now(),#{item.create_user},#{item.ip})",
		"</foreach>;",
		"insert into user_profile ",
		"(user_code,nickname,amount,is_vip,create_time,create_user,update_time,update_user) ",
		"values ",
		"<foreach collection='items' item='item' index='index' separator=','>", 
		"(#{item.user_code},#{item.nickname},#{item.amount},#{item.is_vip},now(),#{item.create_user},now(),#{item.create_user})",
		"</foreach>;",
		"</script>"
	})
	public Integer addUserBatch(@Param(value="items")List<HashMap<String, Object>> models);
	
	@Update("update users set name=#{name}, age=#{age}, update_time=now() where user_code=#{user_code} ")
	public Integer updateUser(UserParams params);
	
	@Update("update user_profile set nickname=#{nickname}, amount=#{amount}, is_vip=#{is_vip}, update_time=now() where user_code=#{user_code} ")
	public Integer updateProfile(UserParams params);
	
	@Delete("delete from users where user_code=#{userCode};delete from user_profile where user_code=#{userCode};")
	public Integer deleteByUserCode(String userCode);
}
